var directivesModule = angular.module('app.directives');

directivesModule.directive('bootstrapPanel', function() {
  return {
    restrict:'EA',
    transclude:true,
    replace: true,
    templateUrl: 'bootstrapPanel.html',
    scope: {
      isOpen: '=?',
      isCollapsable: '=?',
      panelHeaderClass: '=?',
      panelBodyClass: '=?'
    },
    controller: function($scope, $element) {
      var panelTitleElement = $element.find('.panel-heading');

      this.setHeading = function(element) {
        panelTitleElement.append(element);
      };

      this.getCollapsableState = function() {
        return $scope.isCollapsable;
      };
    },
    link: function(scope) {
      if (!scope.panelHeaderClass) {
        scope.panelHeaderClass = 'panel-default';
      }

      if (!scope.panelBodyClass) {
        scope.panelBodyClass = 'panel-body';
      }

      if (!scope.isOpen) {
        scope.isOpen = true;
      }

      scope.getToggleTooltip = function () {
          return scope.isOpen
                    ? 'Collapse'
                    : 'Show';
      };

      scope.toggleOpen = function() {
        if (scope.isCollapsable) {
          scope.isOpen = !scope.isOpen;
        }
      };
    }
  };
})

.directive('panelHeading', function() {
  return {
    restrict: 'EA',
    transclude: true,
    template: '',
    replace: true,
    require: '^bootstrapPanel',
    link: function(scope, element, attr, bootstrapPanelCtrl, transclude) {
      scope.isCollapsable = bootstrapPanelCtrl.getCollapsableState();
      bootstrapPanelCtrl.setHeading(transclude(scope, angular.noop));
    }
  };
});
